/**
 * 创建人:  @author huangpeng    
 * 创建时间:  2024年12月31日 11:23
 * 项目名称:  lemon-blog-cloud
 * 文件名称:  ThirdLoginService
 * 文件描述:  @Description: 第三方登录service
 * <p>
 * All rights Reserved, Designed By huangpeng 
 * @Copyright: 2021-2024
 *
 */
package com.lemon.auth.service;

import com.lemon.common.core.constant.CacheConstants;
import com.lemon.common.core.constant.Constants;
import com.lemon.common.core.constant.SecurityConstants;
import com.lemon.common.core.domain.Result;
import com.lemon.common.core.enums.ResultEnums;
import com.lemon.common.core.exception.ServiceException;
import com.lemon.common.core.text.Convert;
import com.lemon.common.core.utils.ServletUtils;
import com.lemon.common.core.utils.StringUtils;
import com.lemon.common.core.utils.ip.IpUtils;
import com.lemon.common.redis.service.RedisService;
import com.lemon.system.api.RemoteLogService;
import com.lemon.system.api.RemoteUserService;
import com.lemon.system.api.domain.BiUser;
import com.lemon.system.api.domain.BiUserThirdBind;
import com.lemon.system.api.domain.SysLogininfor;
import com.lemon.system.api.model.LoginUser;
import me.zhyd.oauth.enums.AuthUserGender;
import me.zhyd.oauth.model.AuthUser;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 包名称：com.lemon.auth.service
 * 类名称：ThirdLoginService
 * 类描述：第三方登录service
 * 创建人：@author huangpeng
 * 创建时间：2024年12月31日 11:23
 */
@Component
public class ThirdLoginService {

    public static final Logger log = LoggerFactory.getLogger(ThirdLoginService.class);

    @Autowired
    private RemoteLogService remoteLogService;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private RedisService redisService;

    /**
     * 第三方系统登录当前系统
     * @Title: login
     * @Description: 第三方系统登录当前系统
     * @param authUser 第三方系统的用户信息
     * @return: LoginUser
     * @throws:
     * @author: huangpeng
     * @Date: 2024/12/31 11:25
     */
    public LoginUser login(AuthUser authUser) {
        Result<LoginUser> userResult = remoteUserService.getInfoByOriginUid(authUser.getUuid(), authUser.getSource(), SecurityConstants.INNER);
        if (ResultEnums.ERROR.getCode() == userResult.getCode()) {
            throw new ServiceException("通过资料来源平台的当前用户唯一uid来查询用户信息失败，请联系系统管理员！");
        }
        if (userResult.getData() != null) {
            LoginUser loginUser = userResult.getData();
            recordLoginInfo(loginUser.getUsername(), Constants.LOGIN_SUCCESS, "登录成功");
            recordVisitorCount();
            return loginUser;
        } else {
            // 当前系统不存在该用户，需要注册
            BiUser biUser = new BiUser();
            biUser.setUserCode(generateUniqueUserCode(authUser.getSource()));
            biUser.setUserName(authUser.getUsername());
            biUser.setOriginUid(authUser.getUuid());
            biUser.setNickName(authUser.getNickname());
            biUser.setAvatar(authUser.getAvatar());
            biUser.setGender(convertGender(authUser.getGender()));
            biUser.setUserType(Constants.STR_ONE);
            biUser.setStatus(Constants.STR_FOUR);
            biUser.setDataOrigin(convertOrigin(authUser.getSource()));
            biUser.setCommentStatus(Constants.STR_ZERO);
            biUser.setRemark(authUser.getRemark());
            biUser.setEmail(authUser.getEmail());
            biUser.setPassword("lemon_" + LocalDateTime.now().getYear());
            Result<BiUser> registerResult = remoteUserService.registerBaseUserInfo(biUser, SecurityConstants.INNER);
            if (ResultEnums.SUCCESS.getCode() == registerResult.getCode()) {
                // 新增第三方账号绑定信息
                BiUserThirdBind model = new BiUserThirdBind();
                model.setThirdUuid(authUser.getUuid());
                model.setThirdSource(authUser.getSource());
                model.setThirdUname(authUser.getUsername());
                model.setUserId(registerResult.getData().getId());
                model.setStatus(Constants.STR_ONE);
                remoteUserService.insertThirdBind(model, SecurityConstants.INNER);
                recordLoginInfo(authUser.getUsername(), Constants.LOGIN_SUCCESS, "登录成功");
                recordVisitorCount();
                LoginUser baseUserVo = new LoginUser();
                baseUserVo.setBaseUser(registerResult.getData());
                return baseUserVo;
            }
            return null;
        }
    }

    /**
     * 转换用户来源
     * @Title: convertOrigin
     * @Description: 转换用户来源
     * @param source
     * @return: String
     * @throws:
     * @author: huangpeng
     * @Date: 2025/4/10 10:28
     */
    private String convertOrigin(String source) {
        if ("qq".equalsIgnoreCase(source)) {
            return Constants.STR_FOUR;
        } else if ("wechat".equalsIgnoreCase(source)) {
            return Constants.STR_TWO;
        } else if ("gitee".equalsIgnoreCase(source)) {
            return Constants.STR_THREE;
        } else {
            return null;
        }
    }

    /**
     * 记录登录信息
     *
     * @param userCode 用户名
     * @param status 状态
     * @param message 消息内容
     * @return
     */
    public void recordLoginInfo(String userCode, String status, String message)
    {
        SysLogininfor loginInfo = new SysLogininfor();
        loginInfo.setUserName(userCode);
        loginInfo.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
        loginInfo.setMsg(message);
        // 设置是前台登录
        loginInfo.setLoginType(Constants.LOGIN_TYPE_WEB);
        // 日志状态
        if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER))
        {
            loginInfo.setStatus(Constants.LOGIN_SUCCESS_STATUS);
        }
        else if (Constants.LOGIN_FAIL.equals(status))
        {
            loginInfo.setStatus(Constants.LOGIN_FAIL_STATUS);
        }
        remoteLogService.saveLogininfor(loginInfo, SecurityConstants.INNER);
    }

    /**
     * 记录访客数量
     * @Title: recordVisitorCount
     * @Description: 记录访客数量
     * @param
     * @return: void
     * @throws:
     * @author: huangpeng
     * @Date: 2022/9/18 21:55
     */
    private void recordVisitorCount() {
        String visitorCount = Convert.toStr(redisService.getCacheObject(CacheConstants.VISITOR_COUNT_KEY));
        if (org.apache.commons.lang3.StringUtils.isBlank(visitorCount)) {
            redisService.deleteObject(CacheConstants.VISITOR_COUNT_KEY);
            redisService.setCacheObject(CacheConstants.VISITOR_COUNT_KEY, 1);
        } else {
            redisService.setCacheObject(CacheConstants.VISITOR_COUNT_KEY, Integer.parseInt(visitorCount) + 1);
        }
    }

    /**
     * 生成随机的用户登陆名
     * @Title: generateUniqueUserCode
     * @Description: 生成随机的用户登陆名
     * @param source 用户来源
     * @return: String
     * @throws:
     * @author: huangpeng
     * @Date: 2025/4/10 09:37
     */
    public String generateUniqueUserCode(String source) {
        // 生成8位字母数字组合
        String randomCode = source + "_" + RandomStringUtils.randomAlphanumeric(8);
        // 校验登录名是否存在
        Result<LoginUser> userResult = remoteUserService.getInfoByUserCode(randomCode, SecurityConstants.INNER);
        if (ResultEnums.SUCCESS.getCode() == userResult.getCode()) {
            return generateUniqueUserCode(source);
        } else {
            return randomCode;
        }
    }

    /**
     * 转换性别字段
     * @Title: convertGender
     * @Description: 转换性别字段
     * @param gender 性别信息
     * @return: Long
     * @throws:
     * @author: huangpeng
     * @Date: 2025/4/10 10:07
     */
    private Long convertGender(AuthUserGender gender) {
        if (gender == null || gender == AuthUserGender.UNKNOWN) {
            return 2L;
        } else if (gender == AuthUserGender.MALE) {
            return 0L;
        } else if (gender == AuthUserGender.FEMALE) {
            return 1L;
        } else {
            return 2L;
        }
    }

}
